require 'erb'
require 'activesupport'

class NUnitRunner
  include FileTest
  
  def initialize(attributes)
    @compile_target = attributes.fetch(:compilemode, 'debug')
    @source_dir = attributes.fetch(:source, 'source')
    tools_dir = attributes.fetch(:tools, 'tools')
    results_file = attributes.fetch(:results_file, 'results')

    @nunit_exe = File.join(tools_dir, 'nunit', 'bin', "nunit-console.exe").gsub('/','\\') + " /nothread /xml=\"#{results_file}\""
  end
	
  def executeTests(project_names)
    test_files = project_names.map { |project| "\"" + File.expand_path("#{@source_dir}/#{project}/bin/#{@compile_target}/#{project}.dll") + "\"" }
    puts "Executing #{@nunit_exe} on #{test_files.length} assemblies\r\n#{test_files.join("\r\n")}"

    sh "#{@nunit_exe} #{test_files.join(" ")}" if test_files.length > 0
  end
end

class MSBuildRunner
  def self.compile(attributes)
    solution_file  = attributes[:solutionfile]
    version        = attributes.fetch(:clrversion, 'v3.5')
    compile_target = attributes.fetch(:compilemode, 'debug')
    
    framework_dir  = File.join(ENV['windir'].dup, 'Microsoft.NET', 'Framework', version)
    msbuild_file   = File.join(framework_dir, 'msbuild.exe')
    sh "#{msbuild_file} #{solution_file} /maxcpucount /v:m /property:BuildInParallel=false /property:Configuration=#{compile_target} /t:Rebuild"
  end
  
  def self.clean(attributes)
    solution_file  = attributes[:solutionfile]
    version        = attributes.fetch(:clrversion, 'v3.5')
    
    framework_dir  = File.join(ENV['windir'].dup, 'Microsoft.NET', 'Framework', version)
    msbuild_file   = File.join(framework_dir, 'msbuild.exe')

    sh "#{msbuild_file} #{solution_file} /t:Clean"
    end
end

class AsmInfoBuilder
  attr_reader :buildnumber

  def initialize(base_version, properties)
    @properties = properties
    @build_number = base_version + '0'
    @properties['Version'] = @properties['InformationalVersion'] = @build_number;
  end

  def write(file)
    template = %q{using System.Reflection;
using System.Security;

<% @properties.each do |k, v| %>
[assembly: Assembly<%= k.to_s.camelize %>("<%= v %>")]
<% end %>
      }.gsub(/^    /, '')
  
    erb = ERB.new(template, 0, "%<>")
  
    File.open(file, 'w') do |file|
      file.puts erb.result(binding) 
    end
  end
end
